﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using mscook.mvc.Filters;
using mscook.mvc.Models;
using mscook.core.services;
using mscook.mvc.Core;
using mscook.core.domain;
using System.Security.Principal;
using mscook.core.components;
using Newtonsoft.Json.Linq;
using mscook.core.repositories;
using mscook.core;
using QConnectSDK;
using QConnectSDK.Context;

namespace mscook.mvc.Controllers
{

    // [Authorize]
    //[InitializeSimpleMembership]
    public class AccountController : BaseController
    {
        //
        // GET: /Account/Login
        private ILoginUserService iLoginUserService;
        private ISocialUserRelationService iSocialUserRelationService;
        private IFormAuthenticationService iFormAuthenticationService;
        private ILoginUserOfVipRepository iLoginUserOfVipRepository = UnityHelper.UnityToT<ILoginUserOfVipRepository>();

        private IDenglu dengLu;
        public IDenglu OAuthDengLu
        {
            set { dengLu = value; }
            get { return dengLu; }
        }
        private IOAuth oAuth;
        public IOAuth OAuth
        {
            set { oAuth = value; }
            get { return oAuth; }
        }
        public ISocialUserRelationService ISocialUserRelationService
        {
            get { return iSocialUserRelationService; }
        }
        public AccountController(IActionBonusSettingService actionBonusSettingService, IResourceBonusSettingService resourceBonusSettingService, ILoginUserService loginUserService, ISocialUserRelationService iSocialUserRelationService, IFormAuthenticationService iFormAuthenticationService)
            : base(actionBonusSettingService, resourceBonusSettingService, loginUserService)
        {
            this.iLoginUserService = loginUserService;
            this.iSocialUserRelationService = iSocialUserRelationService;
            this.iFormAuthenticationService = iFormAuthenticationService;
            dengLu = new OAuth.Code.Denglu("2437dengCeCgoEE1Z16idcUj1x13b3", "63887243tGjExWcrUzIoCkFtp4uNX6", "MD5");
            oAuth = new QQOAuth();

        }
        public JsonResult ForGetPassword(string userName, string email)
        {
            ValidateResult vr = new ValidateResult();
            LoginUser loginUser = iLoginUserService.SelectLoginUserByLoginName(userName);

            if (loginUser != null && loginUser.Email.Equals(email))
            {
                int randomPwd = new Random().Next(99999, 999999);
                string subject = "美食之窗找回密码";
                string emailBody = string.Format("您的临时密码为{0},请您登录后及时修改密码", randomPwd);
                Email sendEmail = new Email("smtp.ym.163.com", "webmaster@chu.sh", "chu001", subject, emailBody, loginUser.Email);
                if (sendEmail.Send())
                {
                    loginUser.Password = randomPwd.ToString();
                    iLoginUserService.SaveOrUpdate(loginUser);
                    vr.isSucceed = true;
                    vr.message = "邮件已发送,请您及时查看";


                }
                else
                {
                    vr.isSucceed = false;
                    vr.message = "邮件系统异常，请您稍后尝试";
                }

            }
            else
            {
                vr.isSucceed = false;
                vr.message = "根据用户名与邮箱未获取相关用户，请核对信息";
            }

            return new JsonResult { Data = vr };
            //return Content(vr.message);

        }

        public ActionResult DengLu(string pName)
        {
            String url = OAuthDengLu.getAuthUrl(false, pName, null);
            return Redirect(url);
        }

        public ActionResult AcceptToken(String token)
        {
            JObject userInfo = OAuthDengLu.getUserInfoByToken(token);
            // SocialUserRelation socialUserRelation = ISocialUserRelationService.SelectSocialUserRelationByPersonID(userInfo["personID"].Value<string>());
            //2014-01-13 JohnShen 暂时根据用户名获取并更新PersonID
            SocialUserRelation socialUserRelation = ISocialUserRelationService.SelectSocialUserRelationByPersonName((userInfo["screenName"].Value<string>()));
            string personId = userInfo["personID"].Value<string>();

            if (socialUserRelation == null)
            {   //2013-12-05 basilwang TODO 需要传递MediaID,PersonID以及Email等等
                return RedirectToAction("Register", new { MediaID = userInfo["mediaID"].Value<string>(), PersonID = userInfo["personID"].Value<string>(), LoginName = userInfo["screenName"].Value<string>(), Message = "已经绑定网站，请您完善资料,下次可一键登录" });
            }
            else
            {
                //暂时更新PersonId
                //当PersonId不一致时,暂时更新PersonId
                if (!socialUserRelation.PersonID.Equals(personId))
                {
                    socialUserRelation.PersonID = personId;
                    ISocialUserRelationService.SaveOrUpadate(socialUserRelation);
                }

                FormsAuthenticationTicket ticket = populateFormAuthCookie(true, socialUserRelation.LoginName, "");
                this.HttpContext.User = new GenericPrincipal(new FormsIdentity(ticket), null);
                return RedirectToAction("Index", "Home");

            }
        }
        public ActionResult QQLogin(string pName)
        {

            string state = Guid.NewGuid().ToString().Replace("-", "");
            string scope = "get_user_info";
            var authenticationUrl = oAuth.GetAuthorizationUrl(state, scope);
            //request token, request token secret 需要保存起来 
            //在demo演示中，直接保存在全局变量中.真实情况需要网站自己处理 
            Session["requeststate"] = state;
            return Redirect(authenticationUrl);
        }
        public ActionResult QQAcceptToken(String code, String state)
        {
            ActionResult result = null;
            if (code != null)
            {
                string requestState = Session["requeststate"] == null ? "" : Session["requeststate"].ToString();
                if (state == requestState)
                {
                    OAuthUser oAuthUser = OAuth.GetUserInfoByToken(code, state);
                    //SocialUserRelation socialUserRelation = ISocialUserRelationService.SelectSocialUserRelationByPersonID(oAuthUser.PersonID);

                    //2014-01-13 JohnShen 暂时根据用户名获取并更新PersonID
                    //SocialUserRelation socialUserRelation = ISocialUserRelationService.SelectSocialUserRelationByPersonName(oAuthUser.LoginName);
                    
                    //2014-01-14 JohnShen对于现有用户，如果根据PersonId获取到则就根据PersonId获取
                    SocialUserRelation socialUserRelation = ISocialUserRelationService.SelectSocialUserRelationByPersonID(oAuthUser.PersonID); ;
                    if (socialUserRelation==null)
                    {
                         socialUserRelation = ISocialUserRelationService.SelectSocialUserRelationByPersonName(oAuthUser.LoginName);
                    }


                    // string personId = oAuthUser.LoginName;


                    if (socialUserRelation == null)
                    {   //2013-12-05 basilwang TODO 需要传递MediaID,PersonID以及Email等等
                        result = RedirectToAction("Register", new { MediaID = oAuthUser.MediaID, PersonID = oAuthUser.PersonID, LoginName = oAuthUser.LoginName, Message = "已经绑定网站，请您完善资料,下次可一键登录" });
                        Session.Add("oAuthUser", oAuthUser);
                    }
                    else
                    {
                        //暂时更新PersonId
                        //当PersonId不一致时,暂时更新PersonId
                        if (!socialUserRelation.PersonID.Equals(oAuthUser.PersonID))
                        {
                            socialUserRelation.PersonID = oAuthUser.PersonID;
                            ISocialUserRelationService.SaveOrUpadate(socialUserRelation);
                        }

                        FormsAuthenticationTicket ticket = populateFormAuthCookie(true, socialUserRelation.LoginName, "");
                        this.HttpContext.User = new GenericPrincipal(new FormsIdentity(ticket), null);
                        result = RedirectToAction("Index", "Home");

                    }
                }

            }
            else
            {
                result = View();
            }
            return result;
        }
        public ActionResult IsNullByLoginName(String loginName)
        {
           bool result= LoginUserService.IsNullByLoginName(loginName);
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        public ActionResult IsNullByEmail(String email)
        {
            bool result = LoginUserService.IsNullByEmail(email);
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }



        //
        // POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ActionBonusFilter]
        [ValidateAntiForgeryToken]
        //[ActionBonusFilter]暂时取消
        public ActionResult Login(LoginModel model, string returnUrl = "")
        {
            //returnUrl是什么？为null
            LoginUser loginUser = null;
            ValidateResult vr = new ValidateResult() { isSucceed = false, message = "输入数据错误" };
            string loginName = model.UserName;
            //加密后，在ValidateUser中不解密怎么验证的？。。。
            //string password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "MD5");//加密后验证！
            string password = model.Password;
            if (ModelState.IsValid)
            {
                vr = ValidateUser(loginName, password, ref loginUser);
                if (vr.isSucceed)
                {
                    ////2013-10-17 basilwang 在session中存储了currentuser
                    //this.HttpContext.Session["currentuser"] = loginUser;
                    FormsAuthenticationTicket ticket = populateFormAuthCookie(model.RememberMe, loginUser.LoginName, "");
                    this.HttpContext.User = new GenericPrincipal(new FormsIdentity(ticket), null);


                    if (loginUser.UserRole.Equals("systemUser"))
                    {
                        return RedirectToLocal(returnUrl);
                    }

                    return Redirect("/weblogin/home");
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            ModelState.AddModelError("", vr.message);
            return View(model);
        }

        //
        // POST: /Account/LogOff



        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        [AllowAnonymous]
        public ActionResult Register(string MediaID = "", string PersonID = "", string LoginName = "", string Message = "")
        {
            LoginUser Loginuser = new LoginUser();
            ViewData["MediaID"] = MediaID;
            ViewData["PersonID"] = PersonID;
            ViewData["Message"] = Message;
            Loginuser.LoginName = LoginName;
            return View(Loginuser);
        }

        //
        // POST: /Account/Register

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(LoginUser LoginUser, string ConfirmPassword, string returnUrl, string MediaID, string PersonID, string exitLoginName, string exitPsd)
        {
            bool isBinde = (!string.IsNullOrEmpty(exitLoginName)) && (!string.IsNullOrEmpty(exitPsd));
            string ticketName = LoginUser.LoginName;
            ValidateResult vr = new ValidateResult() { isSucceed = false, message = "填写信息有误" };
            if (isBinde || (ModelState.IsValid && ConfirmPassword.Equals(LoginUser.Password)))
            {
                if (!string.IsNullOrEmpty(MediaID) && !string.IsNullOrEmpty(PersonID))//如果是三方登录(不论绑定已有还是重新注册)
                {
                    if (isBinde)
                    {
                        if (iLoginUserService.ValidateLoginUserByPsd(exitLoginName, exitPsd))
                        {
                            SocialUserRelation socialUserRelation = new SocialUserRelation() { LoginName = exitLoginName, MediaID = MediaID, PersonID = PersonID };
                            iSocialUserRelationService.SaveOrUpadate(socialUserRelation);
                            vr.isSucceed = true;
                            ticketName = exitLoginName;
                        }
                        else
                        {
                            vr.isSucceed = false;
                            vr.message = "关联账户信息填写错误";
                        }
                    }
                    else//不绑定已有账户，新增用户
                    {
                        SocialUserRelation socialUserRelation = new SocialUserRelation() { LoginName = LoginUser.LoginName, MediaID = MediaID, PersonID = PersonID };
                        iSocialUserRelationService.SaveOrUpadate(socialUserRelation);
                        vr = SaveNewLoginUser(LoginUser);
                    }
                }
                else//普通注册
                {
                    vr = SaveNewLoginUser(LoginUser);
                }
            }
            if (vr.isSucceed)
            {
                FormsAuthenticationTicket ticket = populateFormAuthCookie(true, ticketName, "");

                this.HttpContext.User = new GenericPrincipal(new FormsIdentity(ticket), null);

                return RedirectToLocal(returnUrl);
            }
            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            ModelState.AddModelError("", vr.message);
            ViewData["MediaID"] = MediaID;
            ViewData["PersonID"] = PersonID;
            return View(LoginUser);
            //return RedirectToAction("Register", new { MediaID = MediaID, PersonID = PersonID });
        }

        private ValidateResult SaveNewLoginUser(LoginUser loginUser)
        {
            ValidateResult vr = new ValidateResult();
            bool isNull = iLoginUserService.IsNullByLoginNameOrEmail(loginUser.LoginName, loginUser.Email);
            if (isNull)
            {
                loginUser.UserRole = "systemUser";
                iLoginUserService.SaveOrUpdate(loginUser);
                vr.isSucceed = true;
            }
            else
            {
                vr.isSucceed = false;
                vr.message = "用户名或邮箱已经存在";
            }
            return vr;


        }


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult BuyResource(string resourceId)
        {
            ValidateResult vr = new ValidateResult();
            if (CurrentUser != null)
            {
                ResourceBonusStrategy resourceBonusStrategy = new ResourceBonusStrategy(resourceId, ResourceBonusSettings, CurrentUser, this.LoginUserService);

                if (resourceBonusStrategy.SetBonus())
                {
                    vr.isSucceed = true;
                    vr.message = "购买成功";
                }
                else
                {
                    vr.isSucceed = false;
                    vr.message = "您的积分不足，请充值或购买Vip后再次尝试";
                }

            }
            else
            {
                vr.isSucceed = false;
                vr.message = "请先登录后购买";
            }

            return new JsonResult { Data = vr };
        }

        [AcceptVerbs(HttpVerbs.Post)]

        public ActionResult BuyVip(string number)
        {
            ValidateResult vr = new ValidateResult();
            if (CurrentUser != null && !string.IsNullOrEmpty(number))
            {
                LoginUserOfVip loginUserOfVip = new LoginUserOfVip();
                loginUserOfVip.Numebr = number;
                loginUserOfVip.LoginUser = CurrentUser;
                iLoginUserOfVipRepository.SaveOrUpdate(loginUserOfVip);
                vr.isSucceed = true;
                vr.message = "申请已经提交，请等待管理员审核";
            }
            else
            {
                vr.isSucceed = false;
                vr.message = "请登录或输入发票号";
            }

            return new JsonResult { Data = vr };
        }



        //
        // POST: /Account/Disassociate

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Disassociate(string provider, string providerUserId)
        {
            string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId? message = null;

            // 只有在当前登录用户是所有者时才取消关联帐户
            if (ownerAccount == User.Identity.Name)
            {
                // 使用事务来防止用户删除其上次使用的登录凭据
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        message = ManageMessageId.RemoveLoginSuccess;
                    }
                }
            }

            return RedirectToAction("Manage", new { Message = message });
        }

        //
        // GET: /Account/Manage

        public ActionResult Manage(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "已更改你的密码。"
                : message == ManageMessageId.SetPasswordSuccess ? "已设置你的密码。"
                : message == ManageMessageId.RemoveLoginSuccess ? "已删除外部登录。"
                : "";
            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.ReturnUrl = Url.Action("Manage");
            return View();
        }

        //
        // POST: /Account/Manage

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Manage(LocalPasswordModel model)
        {
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.HasLocalPassword = hasLocalAccount;
            ViewBag.ReturnUrl = Url.Action("Manage");
            if (hasLocalAccount)
            {
                if (ModelState.IsValid)
                {
                    // 在某些失败方案中，ChangePassword 将引发异常，而不是返回 false。
                    bool changePasswordSucceeded;
                    try
                    {
                        changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                    }
                    catch (Exception)
                    {
                        changePasswordSucceeded = false;
                    }

                    if (changePasswordSucceeded)
                    {
                        return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
                    }
                    else
                    {
                        ModelState.AddModelError("", "当前密码不正确或新密码无效。");
                    }
                }
            }
            else
            {
                // 用户没有本地密码，因此将删除由于缺少
                // OldPassword 字段而导致的所有验证错误
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
                        return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
                    }
                    catch (Exception e)
                    {
                        ModelState.AddModelError("", e);
                    }
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        //
        // POST: /Account/ExternalLogin

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLogin(string provider, string returnUrl)
        {
            return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
        }

        //
        // GET: /Account/ExternalLoginCallback

        [AllowAnonymous]
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            if (!result.IsSuccessful)
            {
                return RedirectToAction("ExternalLoginFailure");
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                return RedirectToLocal(returnUrl);
            }

            if (User.Identity.IsAuthenticated)
            {
                // 如果当前用户已登录，则添加新帐户
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return RedirectToLocal(returnUrl);
            }
            else
            {
                // 该用户是新用户，因此将要求该用户提供所需的成员名称
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl = returnUrl;
                return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
            }
        }

        //
        // POST: /Account/ExternalLoginConfirmation


        [AllowAnonymous]
        public ActionResult ExternalLoginFailure()
        {
            return View();
        }

        [AllowAnonymous]
        [ChildActionOnly]
        public ActionResult ExternalLoginsList(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData);
        }

        [ChildActionOnly]
        public ActionResult RemoveExternalLogins()
        {
            ICollection<OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name);
            List<ExternalLogin> externalLogins = new List<ExternalLogin>();
            foreach (OAuthAccount account in accounts)
            {
                AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider);

                externalLogins.Add(new ExternalLogin
                {
                    Provider = account.Provider,
                    ProviderDisplayName = clientData.DisplayName,
                    ProviderUserId = account.ProviderUserId,
                });
            }

            ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            return PartialView("_RemoveExternalLoginsPartial", externalLogins);
        }

        #region 帮助程序
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
        }

        internal class ExternalLoginResult : ActionResult
        {
            public ExternalLoginResult(string provider, string returnUrl)
            {
                Provider = provider;
                ReturnUrl = returnUrl;
            }

            public string Provider { get; private set; }
            public string ReturnUrl { get; private set; }

            public override void ExecuteResult(ControllerContext context)
            {
                OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
            }
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // 请参见 http://go.microsoft.com/fwlink/?LinkID=177550 以查看
            // 状态代码的完整列表。
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "用户名已存在。请输入其他用户名。";

                case MembershipCreateStatus.DuplicateEmail:
                    return "该电子邮件地址的用户名已存在。请输入其他电子邮件地址。";

                case MembershipCreateStatus.InvalidPassword:
                    return "提供的密码无效。请输入有效的密码值。";

                case MembershipCreateStatus.InvalidEmail:
                    return "提供的电子邮件地址无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidAnswer:
                    return "提供的密码取回答案无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidQuestion:
                    return "提供的密码取回问题无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidUserName:
                    return "提供的用户名无效。请检查该值并重试。";

                case MembershipCreateStatus.ProviderError:
                    return "身份验证提供程序返回了错误。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";

                case MembershipCreateStatus.UserRejected:
                    return "已取消用户创建请求。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";

                default:
                    return "发生未知错误。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";
            }
        }
        #endregion

        protected ValidateResult ValidateUser(string loginName, string pwd, ref LoginUser loginUser)
        {
            ValidateResult vr = new ValidateResult();

            loginUser = LoginUserService.UserLogOnSelectByLoginNameOrEmail(loginName);
            if (loginUser == null)
            {
                vr.message = "未找到相关用户";
                vr.isSucceed = false;
            }
            else
            {
                if (loginUser.Password != pwd)
                {
                    vr.message = "用户名和密码不匹配";
                    vr.isSucceed = false;
                }
                else
                {
                    vr.isSucceed = true;
                }
            }

            return vr;

        }
        protected FormsAuthenticationTicket populateFormAuthCookie(bool isPersistent, string userID, string userType)
        {
            //2013-12-05 basilwang 为了mock不得已创建FormAuthenticationService
            return iFormAuthenticationService.populateFormAuthCookie(isPersistent, userID, userType, this.HttpContext);

        }

        public class ValidateResult
        {
            public bool isSucceed;
            public string message;

        }
    }

}
